# Don't allow Make to delete the uncompressed spritesheet files, so you can have a look at them.
.PRECIOUS: build/%_sheet.png

TARGET = spritesheet.elf
OBJS = main.o romdisk.o
CC = kos-cc
CFLAGS += -std=c11

# Name of spritesheets, assets/spritesheets/foo/ becomes:
# romdisk/foo_sheet.dtex:     paletted texture data of all images in foo/
# romdisk/foo_sheet.dtex.pal: definition of colors in the palette
# romdisk/foo_sheet.txt:      position and dimensions of each sprite within
SPRITESHEET_NAMES := $(notdir $(wildcard assets/spritesheets/*))

all: rm-elf $(TARGET)

include $(KOS_BASE)/Makefile.rules

clean:
	-rm -rf $(TARGET) build/* romdisk.* romdisk/* *.o

rm-elf:
	-rm -f $(TARGET)

$(TARGET): $(OBJS)
	$(CC) -o $(TARGET) $(OBJS) -lkmg -lkosutils -lm

romdisk.o: romdisk.img
	$(KOS_BASE)/utils/bin2o/bin2o romdisk.img romdisk romdisk.o

# romdisk.img will depend on romdisk/foo_sheet.dtex and romdisk_foo_sheet.dtex.pal
SPRITESHEET_RESULT_FILES := $(patsubst %,romdisk/%_sheet.dtex,$(SPRITESHEET_NAMES))
romdisk.img: $(SPRITESHEET_RESULT_FILES) $(addsuffix .pal,$(SPRITESHEET_RESULT_FILES))
	$(KOS_GENROMFS) -f romdisk.img -d romdisk -v

# romdisk/foo_sheet.dtex and romdisk/foo_sheet.dtex.pal are made by this command
romdisk/%_sheet.dtex romdisk/%_sheet.dtex.pal: build/%_sheet.png
	$(info Converting $@ < $<)
	texconv -i $< -o $@ -f PAL8BPP -p build/$*_preview.png

# This rule will assemble all files in the directory assets/spritesheets/foo/ into build/foo_sheet.png.
# build/foo_sheet.png is used as input for the conversion to romdisk/foo_sheet.dtex[.pal] later.
# Store position and dimensions of tiles in romdisk/foo_sheet.txt (gideros format: name, x, y, w, h, dummy1, dummy2).
# Force power of two dimensions (e.g. 64x256) and maximum dimensions 1024x1024 (Dreamcast PVR graphics chip limitations).
# Last options just avoid pro features in TexturePacker that require a license.
# Use --common-divisor-x 4 --common-divisor-y 4 with bought version to use sprite drawing mode without precision problems
build/%_sheet.png: assets/spritesheets/%
	$(info Generating spritesheet $@ from $^)
	TexturePacker --sheet $@ \
		--format gideros --data romdisk/$*_sheet.txt \
		--size-constraints POT --max-width 1024 --max-height 1024 \
		--pack-mode Best --disable-rotation --trim-mode None \
		--trim-sprite-names \
		--algorithm Basic --png-opt-level 0 --extrude 0 --disable-auto-alias \
		$^

run: $(TARGET)
	$(KOS_LOADER) $(TARGET) -n

dist:
	rm -f $(OBJS)
	$(KOS_STRIP) $(TARGET)
